package index

import (
	log2 "gitee.com/yysf_xin/dplog/pkg/slog"
	"github.com/blevesearch/bleve/v2"
	"github.com/blevesearch/bleve/v2/analysis"
	"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
	"github.com/blevesearch/bleve/v2/analysis/analyzer/simple"
	_ "github.com/blevesearch/bleve/v2/analysis/analyzer/standard"
	"github.com/blevesearch/bleve/v2/mapping"
	"log"
	"strconv"
)

type Saver struct {
	Id  int
	Idx bleve.Index
	a   *analysis.Analyzer
	// 基准时间
	base int64
	last int64
}

func (s *Saver) FireMsg(ref *log2.MessageRef) {
	msg := ref.GetRef()
	rs := s.a.Analyze(msg.GetMessage())

	_ = rs
	//for _,v := range rs {
	//	print(util.BytesToString(v.Term))
	//	print(" ")
	//}
	//println()

	id := msg.GetTime().UnixMicro()

	if id == s.last {
		id++
	}

	if s.base == 0 {
		s.base = id
	}

	s.last = id

	docId := strconv.FormatInt(id-s.base, 36)

	_ = docId

	//err := s.Idx.Index(docId, ref)
	////
	//if err != nil {
	//	println(err)
	//	return
	//}

}

func NewSaver(op *SearchOpt) (s *Saver, err error) {

	log.Println("init analyzer", op.Analyzer)

	var (
		mp *mapping.IndexMappingImpl
	)

	mp = bleve.NewIndexMapping()
	cfg := map[string]interface{}{
		"type":  op.Analyzer,
		"dicts": op.Dict,
	}
	err = mp.AddCustomTokenizer(op.Analyzer, cfg)
	if err != nil {
		return
	}
	err = mp.AddCustomAnalyzer(op.Analyzer, cfg)

	if err != nil {
		return
	}

	mp.DefaultAnalyzer = simple.Name

	txt := bleve.NewTextFieldMapping()

	txtK := bleve.NewTextFieldMapping()
	txtK.Analyzer = keyword.Name

	logMapping := bleve.NewDocumentMapping()
	logMapping.AddFieldMappingsAt("Level", txtK)
	logMapping.AddFieldMappingsAt("P", txt)
	logMapping.AddFieldMappingsAt("Thread", txt)
	logMapping.AddFieldMappingsAt("AppName", txt)
	logMapping.AddFieldMappingsAt("TraceID", txt)
	logMapping.AddFieldMappingsAt("Logger", txt)
	logMapping.AddFieldMappingsAt("Method", txt)

	gseTxt := bleve.NewTextFieldMapping()
	gseTxt.Analyzer = op.Analyzer

	logMapping.AddFieldMappingsAt("Message", gseTxt)

	mp.AddDocumentMapping("slog", logMapping)
	mp.StoreDynamic = false

	idx, err := bleve.Open(op.Dir)
	if err != nil {
		idx, err = bleve.New(op.Dir, mp)
		if err != nil {
			return
		}
	}
	//idx,err := bleve.NewMemOnly(mp)

	aa := mp.AnalyzerNamed(op.Analyzer)
	sig := mp.AnalyzerNamed(simple.Name)
	sig.TokenFilters = nil

	log.Println("open index dir", op.Dir)

	s = &Saver{
		Idx: idx,
		a:   aa,
	}

	return
}
